/**
 * @author K老叶(Klaoye)
 * @license Apache 2.0 文件操作类
 */

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class FileOperator {

	public static File chooser(JFrame frame) {// 文件选择窗口
		JFileChooser chooser = new JFileChooser();
		FileSystemView systemView = FileSystemView.getFileSystemView();
		FileFilter filter = new FileNameExtensionFilter("text file", "txt");
		chooser.setCurrentDirectory(systemView.getHomeDirectory());
		chooser.setDialogTitle("请选择文本文件!");
		chooser.setApproveButtonText("选择");
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		chooser.setFileFilter(filter);
		chooser.addChoosableFileFilter(filter);
		chooser.showOpenDialog(frame);
		chooser.setVisible(true);

		return chooser.getSelectedFile();
	}

	public static String encoding(byte[] b) {// 编码判断
		if (b[0] == -27 && b[1] == -101 && b[2] == -98 || b[0] == -17 && b[1] == -69 && b[2] == -65)
			return "UTF-8";
		else if (b[0] == -1 && b[1] == -2)
			return "UTF-16";
		else if (b[0] == -2 && b[1] == -1)
			return "UNICODE";
		else
			return "GBK";
	}

	public static String readFile(File file) throws FileNotFoundException {// 文件读取函数
		InputStream inputStream = new FileInputStream(file);
		byte[] b = new byte[(int) file.length()];// 读取文件流
		try {
			inputStream.read(b);
			inputStream.close();
			if (file.getName().equals(Settings.settings_file.getName())) {//是否为设置文件
				return new String(b, StandardCharsets.UTF_8);
			} else {
				return new String(b, encoding(b));
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean writeFile(File file, String message) {// 文件写入函数
		try {
			if (!file.exists())
				file.createNewFile();
			OutputStream outputStream = new FileOutputStream(file);
			outputStream.write(message.getBytes(StandardCharsets.UTF_8));
			outputStream.close();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			return false;
		}

		return true;
	}
}